package com.electric.qrapp.utils.view

import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import javax.inject.Inject


class LoadingUtils @Inject constructor() : LifecycleEventObserver {
    private var loadingDialog: LoadingDialog? = null

    fun showLoading(context: Context?, isShow: Boolean, msgTip: String? = null) {
        if (context == null) return
        when (isShow) {
            true -> {
                if (loadingDialog == null) {
                    loadingDialog = LoadingDialog(context)
                }
                if (!loadingDialog!!.isShowing) {
                    loadingDialog!!.show()
                    msgTip?.run {
                        loadingDialog!!.setText(this)
                    }
                }
            }
            false -> {
                if (loadingDialog?.isShowing == true) {
                    loadingDialog!!.dismiss()
                }
            }
        }
    }

    fun setText(tipMsg: String) {
        loadingDialog?.run {
            this.setText(tipMsg)
        }
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_DESTROY -> {
                loadingDialog = null
            }
            else -> {}
        }
    }
}


